package com.feicheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.message.LoginMessage;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.common.wx.IWxInfo;
import com.feicheng.common.wx.WxHTTPInterface;
import com.feicheng.persistence.entity.Client;
import com.feicheng.persistence.service.IClientService;
import com.feicheng.service.IFLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service("wx-app-code-login")
public class FWxAppCodeLoginServiceImpl implements IFLoginService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IClientService clientService;

    @Autowired
    HttpSession session;

    @Autowired
    LoginMessage loginMessage;

    @Autowired
    WxHTTPInterface wxHTTPInterface;

    @Resource(name="wx-app")
    IWxInfo appInfo;

    @Override
    public ResultInfo login(String loginParams) {

        /* 取得登录所需的参数 jscode ，转换出现问题时抛出异常，登录逻辑停止。*/
        JSONObject param = null;
        try {
            param = JSONObject.parseObject(loginParams);
        } catch (JSONException exception) {
            throw new SystemException(loginMessage.getE01());
        }

        String code = param.getString(Constant.WX.PARAM.CODE);

        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(wxHTTPInterface.getJscode())
                .append(Constant.WX.PARAM.APPID).append(Constant.HTTP.REQUEST.EQ).append(appInfo.getAppId())
                .append(Constant.HTTP.REQUEST.AD).append(Constant.WX.PARAM.SECRET).append(Constant.HTTP.REQUEST.EQ).append(appInfo.getAppSecret())
                .append(Constant.HTTP.REQUEST.AD)
                .append(Constant.WX.PARAM.GRANT_TYPE)
                .append(Constant.HTTP.REQUEST.EQ)
                .append(Constant.WX.PARAM.AUTHORIZATION_CODE)
                .append(Constant.HTTP.REQUEST.AD)
                .append(Constant.WX.PARAM.JS_CODE)
                .append(Constant.HTTP.REQUEST.EQ).append(code);
        ResponseEntity<String> result = restTemplate.getForEntity(sbUrl.toString(), String.class);

        JSONObject jo = JSON.parseObject(result.getBody());
        if (jo.containsKey(Constant.WX.RESPONSE.OPENID)) {
            String openId = (String) jo.get(Constant.WX.RESPONSE.OPENID);

            QueryWrapper<Client> autorWrapper = new QueryWrapper<Client>();
            autorWrapper.eq(Constant.ENTITY.CLIENT.OPEN_ID, openId);

            List<Client> autorResult = clientService.list(autorWrapper);

            /* 已绑定 */
            if (null != autorResult && 1 == autorResult.size()) {
                Client autor = autorResult.get(0);
                session.setAttribute(Constant.RESULT.CURRENT_CLIENT, autor);
                return ResultInfo.success(autor);
            }

            /* 未绑定 */
            return ResultInfo.bindingFail(openId);


         /* 获取OPENID失败 */
        } else {
            throw new SystemException(loginMessage.getE07());
        }
    }
}
